use dioxus::prelude::*;

use crate::backend::{delete_dog, list_dogs};

#[component]
pub fn Favorites() -> Element {
    // Load the latest favorites list and allow re-fetching after operations
    let favorites = use_resource(|| async move {
        list_dogs().await.unwrap_or_else(|err| {
            tracing::error!("获取收藏列表失败: {err}");
            Vec::new()
        })
    });

    let favorites_list = favorites.cloned().unwrap_or_default();
    let favorites_handle = favorites.clone();

    rsx! {
        div { id: "favorites",
            div { id: "favorites-container",
                if favorites_list.is_empty() {
                    p { "暂无收藏" }
                } else {
                    for (id, url) in favorites_list.into_iter() {
                        div {
                            key: id,
                            class: "favorite-dog",
                            img { src: "{url}" }
                            button {
                                class: "delete",
                                onclick: {
                                    let favorites_handle = favorites_handle.clone();
                                    let id = id;
                                    move |_| {
                                        let favorites_handle = favorites_handle.clone();
                                        spawn(async move {
                                            if let Err(err) = delete_dog(id).await {
                                                tracing::error!("删除收藏失败: {err}");
                                                return;
                                            }
                                            let mut favorites_handle = favorites_handle;
                                            favorites_handle.restart();
                                        });
                                    }
                                },
                                "删除"
                            }
                        }
                    }
                }
            }
        }
    }
}
